package red.internal.core.handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jin Zheng
 * @since 2020-05-10
 */
public class RelayHandler extends ChannelInboundHandlerAdapter
{
	private static Logger logger = LoggerFactory.getLogger(RelayHandler.class);

	private final Channel relayChannel;

	public RelayHandler(Channel relayChannel)
	{
		this.relayChannel = relayChannel;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception
	{
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception
	{
		if (relayChannel.isActive())
		{
			relayChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
	{
		if (relayChannel.isActive())
		{
			relayChannel.writeAndFlush(msg);
		}
		else
		{
			ReferenceCountUtil.release(msg);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
	{
		logger.error("Error,", cause);
		ctx.close();
	}
}
